﻿namespace WPFDBBrowser.Framework
{
    using System;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using Microsoft.Practices.Unity;
    using WPFDBBrowser.Helpers;
    using WPFDBBrowser.Interfaces;
    using WPFDBBrowser.Settings;

    public class ComponentsLoader
    {
        public static void Load(ComponentsSettings components)
        {
            IUnityContainer container = UnityContainerFactory.GetInstance();
            //IUnityContainer container = UnityResolver.GetContainer();
            try
            {
                foreach (ComponentInfo info in components.ComponentInfos)
                {
                    if (!string.IsNullOrEmpty(info.AssemblyName))
                    {
                        Assembly loadedAss = Assembly.LoadFile(Path.Combine(Directory.GetCurrentDirectory(), info.AssemblyName));
                        foreach(ImplementedInterface interf in info.Interfaces)
                        {
                            Type interfType = null;
                            switch (interf.Interface)
                            {
                                case BorwserInterfaces.IDBFactory:
                                    interfType = typeof(IDBFactory);
                                    break;
                            }
                            Type type = loadedAss.GetType(interf.ClassName);
                            bool he = type.GetInterfaces().Contains(interfType);
                            if (interfType != null && type != null && type.GetInterfaces().Contains(interfType))
                            {
                                IDBFactory factory = (IDBFactory)Activator.CreateInstance(type);
                                container.RegisterInstance(interfType, factory.Name, factory);
                            }
                        }
                    }
                }
            }
            catch
            {
            }
        }
    }
}
